<?
	class EntityMeta
	{		
		private $name;
		
		public $table;
		public $props;
        public $idProperty;
		
		function __construct($name)
		{
			$this->name = $name;
			$this->props = array();
			$this->buildMeta();
		}
		
		public function getSql($table = null)
		{
			$table = isset($table) ? $table : $this->table;
			$rows = array();
			$primary = null;
			
			if(empty($table))
				return false;
			
			foreach($this->props as $prop)
			{
				$row = sprintf("`%s` %s ", $prop['sqlName'], $prop['sqlType']);
				
				if($prop['sqlPrimary'])
				{
					$primary = sprintf(" PRIMARY KEY (`%s`) ", $prop['sqlName']);
					$row .= " NOT NULL AUTO_INCREMENT ";
				} 
				else if($prop['not_null'])
				{
					$row .= " NOT NULL";
				} 
				else if(isset($prop['sqlDefault']))
				{
					$row .= $prop['sqlDefault'];
				}
				
				$rows[] = $row;
			}
			
			if(!empty($primary)){
				$rows[] = $primary;
			}
			
			return "CREATE TABLE IF NOT EXISTS `$table` (\n" . implode (",\n", $rows) . "\n) DEFAULT CHARSET=cp1251 AUTO_INCREMENT=1;";
		}
		
		private function buildMeta()
		{
			$reflection = new ReflectionClass($this->name);
			$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
			
			$this->table = $reflection->getConstant('table');
			
			foreach($properties as $property)
			{
				$prop = $this->getPropDoc($property);
				
				$this->props[$prop['name']] = $prop;
			}
		}
		
		private function getPropDoc(ReflectionProperty $property)
		{
			$comment = $property->getDocComment();
			$comment = substr($comment, 3, -2);
			$comment = str_replace("\t", "", $comment);
			$comment = str_replace("\r", "", $comment);
			$comment = str_replace("\n", "", $comment);
			$comment = str_replace("'", '"', $comment);
			
			$json = json_decode('{'.$comment.'}');
			$type = isset($json->type) ? $json->type : 'varchar';
            $isPrimary =  isset($json->primary) ? $json->primary : false;

            if($isPrimary)
            {
                $this->idProperty = $property->getName();
            }
			
			return array(
				'name' => $property->getName(),
				'type' => $type,
				'default' => isset($json->default) ? $json->default : null,
				'length' => isset($json->length) ? $json->length : null,
				'not_null' => isset($json->not_null) ? $json->not_null : false,
				'sqlName' => isset($json->name) ? $json->name : $property->getName(),
				'sqlPrimary' => $isPrimary,
				'sqlType' => isset($json->length) ? "$type($json->length)" : $type,
				'sqlDefault' => isset($json->default) ? " DEFAULT \"$json->default\" " : " DEFAULT NULL "
			);
		}
	}
?>